//$URL: http://deveth0.googlecode.com/svn/trunk/demos/jersey-springsecurity/src/main/java/de/deveth0/demos/jerseyspringsecurity/security/CustomAuthenticationManager.java $
//$Id: CustomAuthenticationManager.java 2 2012-10-23 18:30:23Z amuthmann@gmail.com $
/*
 * Copyright 2012 deveth0.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.deveth0.demos.jerseyspringsecurity.security;

import de.deveth0.demos.jerseyspringsecurity.data.User;
import de.deveth0.demos.jerseyspringsecurity.data.dao.UserDatabase;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;

/**
 * Custom authentication manager which is used to load users from a database
 *
 * @author deveth0
 */
public class CustomAuthenticationManager implements AuthenticationManager {

  @Autowired
  private UserDatabase mUserDatabase;

  public Authentication authenticate(Authentication pAuthentication) throws AuthenticationException {

    User user = mUserDatabase.getUser(pAuthentication.getName());

    // In real life this would be an encrpyted password (SHA512 etc) of course.
    if (StringUtils.equals(user.getPassword(), (String) pAuthentication.getCredentials())) {
      return new UsernamePasswordAuthenticationToken(user, pAuthentication.getCredentials());
    }
    // If authentication failed, return an empty token
    return new UsernamePasswordAuthenticationToken(null, null);
  }
}
